package com.joven.shelltest.utils.pdf;


import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.Rectangle;

import javax.swing.*;
import java.awt.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @Author wzj
 * @Date 2023-08-24 14:34
 **/
public class PdfWaterMarkUtil {

    /**
     * pdf生成水印
     *
     * @param srcPdfPath       插入前的文件路径
     * @param tarPdfPath       插入后的文件路径
     * @param waterMarkContent 水印文案
     * @param numberOfPage     每页需要插入的条数
     * @throws Exception
     */
    public static void addWaterMark(String srcPdfPath, String tarPdfPath, String waterMarkContent, int numberOfPage) throws Exception {
        PdfReader reader = new PdfReader(srcPdfPath);
        PdfStamper stamper = new PdfStamper(reader, Files.newOutputStream(Paths.get(tarPdfPath)));
        PdfGState gs = new PdfGState();

        //设置字体
        BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

        // 设置透明度
        gs.setFillOpacity(0.3f);

        int total = reader.getNumberOfPages() + 1;
        JLabel label = new JLabel();
        label.setText(waterMarkContent);
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        int textH = metrics.getHeight();
        int textW = metrics.stringWidth(label.getText());
        PdfContentByte content;
        Rectangle pageRect = null;
        int interval = -5;
        for (int i = 1; i < total; i++) {
            pageRect = reader.getPageSizeWithRotation(i);
            content = stamper.getOverContent(i);
            content.beginText();
            content.setGState(gs);
            //水印颜色
            content.setColorFill(BaseColor.GRAY);
            //水印字体样式和大小
            content.setFontAndSize(font, 18);
            //插入斜边水印  循环每页插入的条数
//            for (int j = 0; j < numberOfPage; j++) {
//                content.showTextAligned(Element.ALIGN_UNDEFINED, waterMarkContent, 200, 200 * (j + 1), 30);
//            }
            //斜边铺满
            for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 3) {
                for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 2) {
                    content.showTextAligned(Element.ALIGN_LEFT, waterMarkContent, width-textW, height-textH, 30);
                }
            }
            content.endText();
        }
        stamper.close();
        System.out.println("PDF水印添加完成！");
    }

    public static void main(String[] args) throws Exception {
        addWaterMark("D:\\image\\page2.pdf", "D:\\image\\testPdfWater1.pdf", "衢州市爱心养老服务“爱心卡”系统", 2);
    }


}
